<template>
  <div class="app-container">

    <div class="">
      <div style="margin-bottom: 20px;">
        <el-input v-model="listQuery.keyword" placeholder="姓名/用户名等" style="width: 250px;" class="filter-item" />

        <el-button class="" type="primary" icon="el-icon-search" @click="getList">
          搜索
        </el-button>
        <el-button class="" style="margin-left: 10px;" type="warning" icon="el-icon-edit" @click="managertj">
          添加管理员
        </el-button>
      </div>

      <el-table :key="tableKey" v-loading="listLoading" :data="list" max-height="850" border fit highlight-current-row
        style="width: 100%;" @sort-change="sortChange">
        <el-table-column label="ID" prop="user_id" sortable="custom" min-width="150px">
        </el-table-column>

        <el-table-column label="姓名" prop="name" min-width="150px">
        </el-table-column>

        <el-table-column label="用户名" prop="username" min-width="150px">
        </el-table-column>

        <el-table-column label="角色" prop="role_name" min-width="150px">
        </el-table-column>

        <el-table-column label="手机号" prop="phone" min-width="150px">
        </el-table-column>

        <el-table-column label="备注" prop="remark" min-width="150px">
        </el-table-column>

        <el-table-column label="状态" prop="login_status">
          <template slot-scope="scope">
            <span class="el-tag el-tag--success el-tag--medium el-tag--light"
              v-show="scope.row.login_status == 1">正常</span>
            <span class="el-tag el-tag--danger el-tag--medium el-tag--light"
              v-show="scope.row.login_status == 0">禁用</span>
          </template>
        </el-table-column>

        <el-table-column label="创建时间" prop="create_time" min-width="150px">
        </el-table-column>

        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" style="margin-right: 10px;" @click="managerbj(scope.$index)"
              v-if="scope.row.is_super == 0">
              编辑
            </el-button>
            <el-button size="mini" type="danger" @click="managerdel(scope.row.user_id, scope.$index)"
              v-if="scope.row.is_super == 0">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
        @pagination="getList" />

    </div>

    <el-dialog :title="data.id == '0' ? '添加管理员' : '保存管理员'" :visible.sync="createFormBox">
      <el-form ref="form" :model="data" label-width="120px" :rules="rules" style="margin-top: 20px;">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="data.name"></el-input>
        </el-form-item>

        <el-form-item label="角色名称">
          <el-select v-model="data.role_id" filterable placeholder="请选择">
            <el-option v-for="item in rolelist" :key="item.id" :label="item.title" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input prefix-icon="el-icon-key" v-model="data.password" show-password minlength="6" maxlength="20"
            :placeholder="data.id == 0 ? '不填默认123456，密码6-20位，由数字、字母、符号组成' : '不填默认为之前的密码，密码6-20位，由数字、字母、符号组成'"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="password_confim">
          <el-input prefix-icon="el-icon-key" v-model="data.password_confim" show-password minlength="6" maxlength="20"
            placeholder="密码6-20位，由数字、字母、符号组成"></el-input>
        </el-form-item>

        <!-- <el-form-item label="操作秘钥" prop="handle_password">
                <el-input prefix-icon="el-icon-key" v-model="data.handle_password" minlength="6" maxlength="20" :placeholder="data.id == 0 ? '秘钥6-20位，由数字、字母、符号组成' : '不填默认为之前的秘钥，秘钥6-20位，由数字、字母、符号组成'"></el-input>
                <div>{{data.old_handle_password}}</div>
            </el-form-item> -->

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="data.phone" maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="data.remark"></el-input>
        </el-form-item>

        <el-form-item label="状态" prop="login_status">
          <el-radio v-model="data.login_status" :label="1">正常</el-radio>
          <el-radio v-model="data.login_status" :label="0">禁用</el-radio>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="managersave()">
            <span v-if="data.user_id == 0">添加</span>
            <span v-if="data.user_id > 0">保存</span>
          </el-button>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">

      </div>
    </el-dialog>


  </div>
</template>
<style>
.create-form-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
}

.create-form-des {
  font-size: 13px;
  color: #aaa;
}
</style>
<script>
import { rolelist, managerlist, manageradd, manageredit, managerdel } from '@/api/auth'
import { MessageBox, Message } from 'element-ui'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { parseTime } from '@/utils'

export default {
  name: 'manager-list',
  components: { Pagination },
  directives: { waves },
  filters: {
  },

  data() {
    //验证用户名
    var checkUsername = (rule, value, callback) => {
      const usernameReg = /^\w{4,20}$/
      setTimeout(() => {
        if (usernameReg.test(value)) {
          callback()
        } else {
          callback(new Error('用户名4-20位，可由数字、字母、下划线组成'))
        }
      }, 100)
    };

    //验证手机号的规则
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[2|3|4|5|6|7|8|9][0-9]{9}$/

      if (value.length == 0) {
        callback()
      } else {
        if (phoneReg.test(value)) {
          callback()
        } else {
          callback(new Error('手机号码格式不正确'))
        }
      }
    };

    //验证密码
    var checkPassword = (rule, value, callback) => {
      const pwReg = /^[\\~!@#$%^&*()-_=+|{}\[\],.?\/:;\'\"\d\w]{6,20}$/

      if (value.length == 0) {
        callback()
      } else {
        setTimeout(() => {
          if (pwReg.test(value)) {
            callback()
          } else {
            callback(new Error('密码格式不正确，密码6-20位，由数字、字母、符号组成'))
          }
        }, 100)
      }
    };

    //验证两次密码是否一致
    var checkPasswordConfim = (rule, value, callback) => {
      if (this.data.password.length == 0) {
        callback()
      } else {
        if (value != this.data.password) {
          callback(new Error('两次密码不一致！'))
        } else {
          callback()
        }
      }
    };
    return {
      rolelist: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        keyword: "",//搜索
        sort: 'id_desc'//默认的排序
      },
      data: {
        user_id: 0,
        name: "",
        role_id: "",
        username: "",
        password: "",
        password_confim: "",
        phone: "",
        login_status: 1,
      },
      createFormBox: false,//创建表单盒子显示和隐藏
      dialogStatus: '',
      dialogPvVisible: false,
      pvData: [],
      rules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: checkUsername }
        ],
        phone: [
          { required: false, trigger: 'blur', validator: checkPhone }
        ],
        password: [
          { required: false, message: '请输入密码', trigger: 'blur' },
          { trigger: 'blur', validator: checkPassword }
        ],
        password_confim: [
          { required: false, message: '请输入确认密码', trigger: 'blur' },
          { trigger: 'blur', validator: checkPasswordConfim }
        ],
      },
    }
  },
  created() {
    this.getList()
    this.getRoleList()
  },
  methods: {
    getList() {
      this.listLoading = true
      managerlist(this.listQuery).then(response => {
        setTimeout(() => {
          this.listLoading = false
        }, 100)

        let code = response.code;
        let msg = response.msg;
        if (code == 200) {
          this.list = response.response.data;
          this.total = response.response.total;
        } else {
          this.$message({
            message: msg,
            type: 'error'
          });
        }
      }).catch(() => {
        this.listLoading = false
      });
    },
    //这里是改变排序的
    sortChange(data) {
      const { prop, order } = data
      if (order === 'ascending') {
        this.listQuery.sort = prop + '_asc'
      } else {
        this.listQuery.sort = prop + '_desc'
      }
      this.getList();
    },
    getRoleList() {
      this.listLoading = true
      rolelist(this.listQuery).then(response => {
        if (response.code == 200) {
          this.rolelist = response.response;
        }
        setTimeout(() => {
          this.listLoading = false
        }, 100)
      })
    },
    //点击创建管理员按钮
    managertj() {
      this.createFormBox = true;
      this.data= {
        user_id: 0,
        name: "",
        role_id: "",
        username: "",
        password: "",
        password_confim: "",
        phone: "",
        login_status: 1,
      },
      this.data.id = 0;

    },
    //点击编辑管理员按钮
    managerbj(index) {
      this.data = this.list[index];
      console.log(this.list[index])
      this.createFormBox = true;
    },
    //创建管理员/修改管理员(确认按钮)
    managersave() {
      var id = this.data.id;
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (id == 0) {//创建管理员
            this.manageradd();
          } else {//保存管理员
            this.manageredit();
          }
        }
      })
    },
    //创建管理员
    manageradd() {
      manageradd(this.data).then((res) => {
        var code = res.code;
        var msg = res.msg;
        if (code == 200) {
          this.getList();
          this.$refs['form'].resetFields();
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
      })
    },
    //保存管理员
    manageredit() {
      manageredit(this.data).then((res) => {
        var code = res.code;
        var msg = res.msg;
        if (code == 200) {
          this.getList();
          this.$message.success(msg);
        } else {
          this.$message.error(msg);
        }
      })
    },
    //删除管理员
    managerdel(id, index) {
      this.$confirm('确定删除此管理员吗？！', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        managerdel({ user_id: id }).then(response => {
          var code = response.code;
          var msg = response.msg;
          if (code == 200) {
            this.list.splice(index, 1)
            this.total = this.total - 1;
            this.$message({
              message: msg,
              type: 'success'
            });
          } else {
            this.$message({
              message: msg,
              type: 'error'
            });
          }
        })
      });
    },
  }
}
</script>
